﻿using System;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;
using System.IO;

namespace SharePointProxyPage.Layouts.SharePointProxyPage
{
    public partial class Proxy : LayoutsPageBase
    {
        protected override void OnInit(EventArgs e)
        {
            ProcessProxyRequest();
        }

        protected void ThrowSharePointError(string errorMessage)
        {
            throw new SPException(errorMessage);
        }

        protected void ProcessProxyRequest()
        {
            var proxyURL = string.Empty;
            try
            {
                proxyURL = HttpUtility.UrlDecode(Request.QueryString["u"]);
            }
            catch
            {
                ThrowSharePointError("No URL provided.");
                return;
            }

            if (string.IsNullOrEmpty(proxyURL))
            {
                ThrowSharePointError("No URL provided.");
                return;
            }

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(proxyURL);
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode.ToString().ToLower() == "ok")
                {
                    var contentType = response.ContentType;
                    var content = response.GetResponseStream();
                    if (content != null)
                    {
                        var contentReader = new StreamReader(content);
                        Response.ClearHeaders();
                        Response.Clear();
                        Response.ContentType = contentType;
                        Response.Write(contentReader.ReadToEnd());
                        Response.Flush();
                    }
                    else
                    {
                        ThrowSharePointError("Error retrieving specified URL.");
                        return;
                    }

                }
                else
                {
                    ThrowSharePointError("Error retrieving specified URL.");
                    return;
                }
            }
            catch
            {
                ThrowSharePointError("Error retrieving specified URL.");
                return;
            }
        }
    }
}
